package com.fone.player.online.activity;

import java.net.MalformedURLException;
import java.net.URL;

import android.content.Intent;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.CookieManager;
import android.webkit.DownloadListener;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.TextView;

import com.fone.player.R;
import com.fone.player.activity.BaseActivity;
import com.fone.player.activity.main.SplashActivity;
import com.fone.player.client.Configure;
import com.fone.player.client.Reporter;
import com.fone.player.client.Request;
import com.fone.player.entity.Download;
import com.fone.player.entity.SoftInfo;
import com.fone.player.sns.ISNSShareManager.ShareStateListener;
import com.fone.player.sns.bean.SNSUserInfo;
import com.fone.player.sns.bean.ShareInfo;
import com.fone.player.sns.impl.SNSShareManager;
import com.fone.player.storage.StorageModule;
import com.fone.player.util.ActivityQueue;
import com.fone.player.util.FoneUtil;
import com.fone.player.util.FoneWebViewClient;
import com.fone.player.util.L;
import com.fone.player.util.ScreenUtil;
import com.fone.player.util.WebViewAction;
import com.fone.player.view.SelectSharePopwindow;

public class WebActivity extends BaseActivity {
	/** 日志标签 */
	private static final String TAG = "WebActivity";
	
	private View titleView;
	private Button mLeftBt;
	private Button mRightBt;
	private TextView mTitleTv;
	
	private boolean isFromNotication = false;
	
	private String url;
	private String name;
	private String picurl;
	
	private WebView mWebView;
	
	private SelectSharePopwindow mSelectSharePopwindow;
	private MyShareStateListener mShareStateListener;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);
        
		Intent intent = getIntent();
		isFromNotication = intent.getBooleanExtra("notice", false);
		url = intent.getStringExtra("url");
		name = intent.getStringExtra("name");
		String cid = intent.getStringExtra("cid");
		int comefrom = intent.getIntExtra("comefrom", -1);
		
		//如果是来自外部通知的 上报到H5
		L.v(TAG, "onCreate", " Reporter  cid : " + cid +" comefrom : " + comefrom );
		if((!TextUtils.isEmpty(cid)) && comefrom!=-1){
			Reporter.logH5Enter(cid, "", comefrom);
			Reporter.logH5Exit();
		}
		
//		weibourl ="----------";
		initView();
	}
	
	private void initView() {
		// TODO 初始化控件
		
		titleView = (View)findViewById(R.web.common_title);
		
		mLeftBt = (Button) findViewById(R.id.common_title_left_bt);
		mRightBt = (Button) findViewById(R.id.common_title_right_bt);
		mTitleTv = (TextView) findViewById(R.id.common_left_title_tv);
		
//		if (TextUtils.isEmpty(weibourl)) {
//			mRightBt.setVisibility(View.GONE);
//		}else{
			mRightBt.setVisibility(View.VISIBLE);
			mRightBt.setText("分享");
//		}
		
		
		mTitleTv.setVisibility(View.VISIBLE);
		mTitleTv.setText(name);
		
		mLeftBt.setOnClickListener(new BtnOnClicker());
		mRightBt.setOnClickListener(new BtnOnClicker());
		
		mWebView = (WebView)findViewById(R.web.webview);
		mWebView.setBackgroundColor(0);
        //设置WebView属性，能够执行Javascript脚本  
		mWebView.getSettings().setJavaScriptEnabled(true);  
        //加载需要显示的网页  
		mWebView.loadUrl(url); 
		mWebView.setWebViewClient(new FoneWebViewClient());
		mWebView.addJavascriptInterface(new WebViewAction(WebActivity.this), "Fone");
		mWebView.setDownloadListener(new MyWebViewDownLoadListener());
	}
	
	private class BtnOnClicker implements OnClickListener{

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.common_title_left_bt:
				finish();
				break;
				
			case R.id.common_title_right_bt:
//				showShortToast("分享按钮相应点击");
				showSharePopWindow();
				break;

			default:
				break;
			}
		}
		
	}
	
	// 展示分享的popwindow
	private void showSharePopWindow() {
		ShareInfo info = new ShareInfo(SNSShareManager.TENCENT_WEIXIN_FRIEND_TYPE);
		String share_word_prefix = getResources().getString(R.string.select_share_word_prefix);
		String share_link_address = getResources().getString(R.string.select_share_link_address);
		info.title = name;
		info.titleUrl = share_link_address;
		info.text = share_word_prefix + name;
		info.videoUrl = FoneUtil.getAbsoluteUrl(Configure.getEndPoint(), null, url);
		info.imageUrl = picurl;
		info.site = "100tv";
		info.siteUrl = share_link_address;

		if (mShareStateListener == null) {
			mShareStateListener = new MyShareStateListener();
		}
		if (mSelectSharePopwindow == null) {
			Rect frame = new Rect();
			this.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame); // mActivity指当前的activity
			int Height = ScreenUtil.getScreenHeightPix(this) - titleView.getHeight() - frame.top;
			mSelectSharePopwindow = new SelectSharePopwindow(this, Height, ScreenUtil.getScreenWidthPix(this), mShareStateListener);
		}

		mSelectSharePopwindow.show(titleView, info);

	}
	
	// 分享的监听器
	private class MyShareStateListener implements ShareStateListener {

		@Override
		public void shareAction(int action, String info) {
			switch (action) {
			case ShareStateListener.SHARING:
				L.v(TAG, "shareAction", "SHARING");
				break;
			case ShareStateListener.SHARE_SUCCESS:
				L.v(TAG, "shareAction", "SHARE_SUCCESS");
				break;
			case ShareStateListener.SHARE_FAILED:
				L.v(TAG, "shareAction", "SHARE_FAILED");
				FoneUtil.showToast(mContext, info);
				break;
			case ShareStateListener.SHARE_CANCEL:
				L.v(TAG, "shareAction", "SHARE_CANCEL");
				break;
			default:
				break;
			}

		}

		@Override
		public void onUserInfoComplete(SNSUserInfo user) {

		}

	}
	

	@Override
	public void finish() {
		// 未启动应用的通知过来  要打开应用
		if (isFromNotication && ActivityQueue.getSize() <= 1) {
			Intent i = new Intent(WebActivity.this, SplashActivity.class);
			startActivity(i);
		}
		super.finish();
	}
	
	
	@Override
	protected void onDestroy() {
		if (mWebView != null) {
			mWebView.stopLoading();
			mWebView.clearCache(true);
			mWebView.clearView();
			mWebView.destroy();
			mWebView = null;
		}
		CookieManager.getInstance().removeAllCookie();
		super.onDestroy();
	}
	
	private class MyWebViewDownLoadListener implements DownloadListener {  
		  
        @Override  
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,  
                                    long contentLength) { 
        	
        	Log.i("onDownloadStart", "onDownloadStart " + url);
        	String end ="";
//        	URL hp;
        	String fileName = url.substring(url.lastIndexOf("/")+1);
        	
        	Log.i("onDownloadStart", "fileName " + fileName);
        	
//			try {
//				hp = new URL(url);
//				fileName = hp.getFile();
//			} catch (MalformedURLException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
    		
    		
    		if (fileName != null) {
    			
    			end=fileName.substring(fileName.lastIndexOf(".")+1,fileName.length()).toLowerCase(); 
    		}

        	if (end.equals("apk")) {
   
        		if (FoneUtil.isNetOkWithToast(WebActivity.this)) {
        		

					Download download = new Download();
					download.setDownloadIsShowRunningNotification(true);
					download.setDownloadUrl(url);
					download.setDownloadFileName(fileName);
					download.setDownloadNotification(WebActivity.this);
					download.setDownloadIsInstall(true);
					download.setDownloadIsErrorToast(true);
					download.setDownloadIsLimitSpeed(false);
					download.setDownloadType(Download.DOWNLOAD_RECOMMEND);
					int result = StorageModule.getInstance().addFileDownload(
							download);
					switch (result) {
						case 1:
							FoneUtil.showToast(WebActivity.this, "已经开始下载" + fileName
								+ "应用");
							break;
						case -1:
							FoneUtil.showToast(WebActivity.this, "该任务已经在下载队列");
							break;
						default:
							break;
					}
        		}
				
			} else {
				
				Uri uri = Uri.parse(url); 
	            Intent intent = new Intent(Intent.ACTION_VIEW, uri);  
	            startActivity(intent); 
				
			}
        }  
  
    }  
	
}
